package com.atguigu.guli.api.gateway;

import com.atguigu.guli.api.gateway.handler.GlobalJsonExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.stream.Collectors;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class , args);
    }
    //将全局异常处理器注入到容器中
    @Bean
    @Order(-1)
    public GlobalJsonExceptionHandler jsonExceptionHandler(ErrorAttributes errorAttributes,
                                                           org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
                                                           ServerProperties serverProperties,
                                                           ObjectProvider<ViewResolver> viewResolvers,
                                                           ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext){

        GlobalJsonExceptionHandler handler = new GlobalJsonExceptionHandler(errorAttributes, resourceProperties,
                serverProperties.getError(), applicationContext);
        handler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        handler.setMessageWriters(serverCodecConfigurer.getWriters());
        handler.setMessageReaders(serverCodecConfigurer.getReaders());
        return handler;
    }

}
